import store from '@/store'
import {SWebSocket} from "./WebSocket/WebSocket";

let ws = websocketUrl + '/demo/webSocketServer';
let broadcastAddress = '/topic/message';
let broadcastInfo = '/user/queue/message';
let client = null;
let ackUrl = '/ack/'

export function createWebSocket() {
  let userInfo = sessionStorage.getItem("userInfo");
  let Authorization = JSON.parse(userInfo || "{}").Authorization || ""
  if (Authorization) {
    // 创建连接
    new SWebSocket(ws, broadcastAddress, log => {
      dataProcessing(log)
    }, {Authorization}).then(stompClient => {
      client = stompClient;
      startSubscribe(stompClient);
    })

    // 订阅
    function startSubscribe() {
      client && client.subscribe(broadcastInfo, log => {
        dataProcessing(log)
      });
    }

    // 消息处理
    function dataProcessing(log) {
      let data = JSON.parse(log.body);
      if (data.type === 'SYSTEM') {
        store.commit('log/ADD_SYSTEM_LOG', JSON.parse(log.body))
      } else {
        store.commit('log/ADD_BUSINESS_LOG', JSON.parse(log.body))
      }
      if (data.persistent) {
        sendMessage(data['msgId'])
      }
    }

    // 回值
    function sendMessage(id) {
      client && client.send(ackUrl + id, {}, '');
    }
  }
}

// 断开连接
export function closeWs() {
  client && client.disconnect();
}
